package com.cliff.joinme;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;

import com.androidquery.AQuery;
import com.androidquery.callback.BitmapAjaxCallback;
import com.androidquery.callback.ImageOptions;
import com.androidquery.util.AQUtility;
import com.cliff.joinme.toolkit.MediaStoreHelper;
import com.cliff.joinme.toolkit.data.MediaItem;

public class BrowseImageActivity extends BrowseBaseActivity implements OnItemClickListener {

	protected AQuery gridAq = null;
//	protected ImageOptions imageOptions = new ImageOptions(); 

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_browseimage);

		itemList = MediaStoreHelper.getInstance().getImageItemList(this);
		initGridView();		
	}

	protected void initGridView() {
		AQUtility.cleanCacheAsync(this, 0, 0);
		BitmapAjaxCallback.clearCache();

		gridAq = new AQuery(this);
//		imageOptions.targetWidth = 100;
//		imageOptions.fallback = R.drawable.image_missing;
//		imageOptions.animation = AQuery.FADE_IN;
//		imageOptions.ratio = 1.0f;
		
		ArrayAdapter<MediaItem> aa = new ArrayAdapter<MediaItem>(this,
				R.layout.item_grid_item, itemList) {
			public View getView(int position, View convertView, ViewGroup parent) {
				if (convertView == null) {
					convertView = getLayoutInflater().inflate(
							R.layout.item_grid_item, parent, false);
				}
				MediaItem item = getItem(position);
				String tbUrl = item.filePathName;
				AQuery gridItemAq = gridAq.recycle(convertView);
				Bitmap placeholder = gridItemAq.getCachedImage(R.drawable.image_ph);

				if (gridItemAq.shouldDelay(position, convertView, parent, tbUrl)) {
					gridItemAq.id(R.id.tb).image(placeholder, 1.0f);
				} else {
					gridItemAq.id(R.id.tb).progress(R.id.progress)
					.image(tbUrl, true, true, 100, R.drawable.image_missing, null, AQuery.FADE_IN, 1.0f/1.0f);					
//					.image(tbUrl, imageOptions);
				}
				return convertView;
			}
		};
		gridAq.id(R.id.gridViewImages).adapter(aa);
		gridAq.id(R.id.gridViewImages).itemClicked(this);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO Auto-generated method stub
        Intent intent = new Intent(BrowseImageActivity.this, PlayImageActivity.class);
        intent.putStringArrayListExtra(Constants.EXTRA_NAME_DATALIST, getFilePathNameList());
        intent.putExtra(Constants.EXTRA_NAME_POSITION, position);        
        startActivity(intent);
	}
}
